package com.vineetmanohar.nitrogen;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class FileGenerator {
	public static void generateFile(GeneratedPath generatedPath,
			File inputBasedir, File outputBasedir) {
		String inputPath = generatedPath.getInputPath();
		String outputPath = generatedPath.getGeneratedPath();
		Model codeGenerationContext = generatedPath.getPathGenerationContext();

		generateFile(inputPath, outputPath, codeGenerationContext,
				inputBasedir, outputBasedir);

	}

	/**
	 * Generate a file specified by the generated path
	 * 
	 * @param generatedPath
	 */
	public static void generateFile(String inputPath, String outputPath,
			Model codeGenerationContext, File inputBasedir, File outputBasedir) {
		if (codeGenerationContext == null) {
			throw new NitrogenException("Code generation context is null", null);
		}

		if (outputBasedir == null) {
			throw new NitrogenException(
					"Output directory for file generation is null", null);
		}

		// input
		File inputFile = new File(inputBasedir, inputPath.replaceAll("/",
				File.separator));

		String inputText;
		try {
			inputText = FileUtils.readFileToString(inputFile);
		} catch (IOException e) {
			throw new NitrogenException("Unable to read input file: "
					+ inputFile, e);
		}

		// output
		File outputFile = new File(outputBasedir, outputPath);
		if (!outputFile.getParentFile().exists()
				&& !outputFile.getParentFile().mkdirs()) {
			throw new NitrogenException(
					"Unable to create output directory for file, please check permissions: "
							+ outputFile, null);
		}

		// call code generation
		String outputText = TextGenerator.generateCode(codeGenerationContext,
				inputText);
		try {
			FileUtils.writeStringToFile(outputFile, outputText);
		} catch (IOException e) {
			throw new NitrogenException("Unable to write output to file: "
					+ outputFile, e);
		}
	}
}